package com.haian.slidealbum.control;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.haian.slidealbum.R;
import com.haian.slidealbum.common.ConstCommon;
import com.haian.slidealbum.model.adapter.AdapterAlbumManage;
import com.haian.slidealbum.model.helper.DBHandler;
import com.haian.slidealbum.model.object.ObjectAlbum;
import com.haian.slidealbum.model.object.ObjectImage;

public class AlbumManageActivity extends Activity implements OnClickListener {
	TextView txtItemSelected;
	ImageView btnAdd, btnEdit, btnSetting;
	GridView listAlbum;
	AdapterAlbumManage adapter;
	private static int CREATE_NEW_ALBUM = 1, UPDATE_ALBUM = 2;
	ArrayList<ObjectAlbum> arrayAlbum, listAlbumSelected;
	Context mContext;
	Dialog dialog;
	String cbSelected_Selected;

	// _______________________ System Fuction ________________________________

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_album_manage);
		initDB();
		DBHandler.initdb(mContext);
		initWidget();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnAdd:
			listAlbumSelected.clear();
			txtItemSelected.setVisibility(View.INVISIBLE);
			showDialogSelectAddressImport();
			break;
		case R.id.btnEdit:
			showScreenDelete();
			break;
		case R.id.btnSetting:
			Intent intent = new Intent(mContext, WidgetSettingsActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		if (FlickrAlbumActivity.KEY_FOR_RESUM_ALBUM) {
			FlickrAlbumActivity.KEY_FOR_RESUM_ALBUM = false;
			if (FlickrAlbumActivity.KEY_ID_RESUM_ALBUM > 0) {
				updateListAlbum(FlickrAlbumActivity.KEY_ID_RESUM_ALBUM);
				FlickrAlbumActivity.KEY_ID_RESUM_ALBUM = 0;
				adapter.notifyDataSetChanged();
			}
		}
		super.onResume();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CREATE_NEW_ALBUM) {
			if (resultCode == RESULT_OK) {
				String maxIdAlbum = data
						.getStringExtra(ConstCommon.KEY_RESULT_ID_ALBUM);
				if (maxIdAlbum != null && maxIdAlbum.equals("") == false) {
					updateListAlbum(Integer.parseInt(maxIdAlbum));
					adapter.notifyDataSetChanged();
				}
			}
		}

		if (requestCode == UPDATE_ALBUM) {
			if (resultCode == RESULT_OK) {
				int idAlbum = data.getIntExtra(ConstCommon.KEY_RESULT_ID_ALBUM,
						0);
				String nameAlbum = data
						.getStringExtra(ConstCommon.KEY_RESULT_NAME_ALBUM);
				ArrayList<ObjectAlbum> arrayAlbumToUpdate = new ArrayList<ObjectAlbum>();
				arrayAlbumToUpdate = arrayAlbum;
				for (int i = 0; i < arrayAlbumToUpdate.size(); i++) {
					ObjectAlbum objectAlbum = new ObjectAlbum();
					objectAlbum = arrayAlbumToUpdate.get(i);
					if (objectAlbum.getIdAlbum() == idAlbum) {
						objectAlbum.setNameAlbum(nameAlbum);
						arrayAlbum.remove(i);
						arrayAlbum.add(i, objectAlbum);
						break;
					}
				}
				adapter.notifyDataSetChanged();
			}
		}
	}

	// _______________________________- Custom Function ________________________

	void showScreenDelete() {
		try {
			if (listAlbumSelected.size() > 0) {
				showDialogDeleteAlbum();
			} else if (arrayAlbum.size() > 0) {
				ArrayList<ObjectAlbum> arrayAlbumTemp = new ArrayList<ObjectAlbum>();
				for (int i = 0; i < arrayAlbum.size(); i++) {
					ObjectAlbum mObjectAlbum = new ObjectAlbum();
					mObjectAlbum = arrayAlbum.get(i);
					mObjectAlbum.setCheckDelete(true);
					mObjectAlbum.setSelected(false);
					arrayAlbumTemp.add(mObjectAlbum);
				}
				arrayAlbum.clear();
				arrayAlbum.addAll(arrayAlbumTemp);
				adapter.notifyDataSetChanged();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public ArrayList<ObjectAlbum> getListAlbumSelected() {
		listAlbumSelected = new ArrayList<ObjectAlbum>();
		try {
			if (arrayAlbum.size() > 0) {
				for (int i = 0; i < arrayAlbum.size(); i++) {
					if (arrayAlbum.get(i).isSelected()) {
						listAlbumSelected.add(arrayAlbum.get(i));
					}
				}
			}
			txtItemSelected.setVisibility(View.VISIBLE);
			txtItemSelected.setText(listAlbumSelected.size() + " "
					+ getResources().getString(R.string.album_selected));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return listAlbumSelected;
	}

	void showDialogDeleteAlbum() {
		try {
			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.delete_album));
			dialog.setContentView(R.layout.dialog_delete);
			Button dialog_BtnYes = (Button) dialog
					.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog
					.findViewById(R.id.dialog_BtnNo);
			dialog_BtnYes.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {

					if (listAlbumSelected.size() > 0) {
						for (int i = 0; i < listAlbumSelected.size(); i++) {
							ObjectAlbum mObjectAlbum = listAlbumSelected.get(i);
							DBHandler.deleteAlbum(mContext,
									mObjectAlbum.getIdAlbum());
							arrayAlbum.remove(mObjectAlbum);
						}
						ArrayList<ObjectAlbum> arrayAlbumTemp = new ArrayList<ObjectAlbum>();
						for (int i = 0; i < arrayAlbum.size(); i++) {
							ObjectAlbum mObjectAlbum = new ObjectAlbum();
							mObjectAlbum = arrayAlbum.get(i);
							mObjectAlbum.setCheckDelete(false);
							mObjectAlbum.setSelected(false);
							arrayAlbumTemp.add(mObjectAlbum);
						}
						arrayAlbum.clear();
						arrayAlbum.addAll(arrayAlbumTemp);
						adapter.notifyDataSetChanged();
						listAlbumSelected.clear();
						txtItemSelected.setVisibility(View.INVISIBLE);
					}
					dialog.dismiss();
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void initDB() {
		mContext = this;
		arrayAlbum = new ArrayList<ObjectAlbum>();
		listAlbumSelected = new ArrayList<ObjectAlbum>();
	}

	void showDialogUpdateAlbum(final int idAlbum) {
		try {
			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.change_album));
			dialog.setContentView(R.layout.dialog_album_info);
			final EditText dialogNameAlbum = (EditText) dialog
					.findViewById(R.id.dialogNameAlbum);
			final CheckBox cbCurrentAlbum = (CheckBox) dialog
					.findViewById(R.id.cbCurrentAlbum);
			Button dialog_BtnYes = (Button) dialog
					.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog
					.findViewById(R.id.dialog_BtnNo);
			Cursor mCursorAlbum = DBHandler.getAlbumById(mContext, idAlbum);
			if (mCursorAlbum.moveToFirst()) {
				dialogNameAlbum.setText(mCursorAlbum.getString(1));
				cbCurrentAlbum.setChecked(false);
				if (mCursorAlbum.getString(2).equals("1")) {
					cbCurrentAlbum.setChecked(true);
					cbCurrentAlbum.setEnabled(false);
				}
			}
			dialog_BtnYes.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String nameAlbum = "";
					String currentAlbum = "1";
					nameAlbum = dialogNameAlbum.getText().toString();
					if (cbCurrentAlbum.isChecked()) {
						currentAlbum = "1";
						DBHandler.disableCurrentAlbum(mContext);
					} else {
						currentAlbum = "0";
					}

					DBHandler.updateAlbum(mContext, idAlbum, nameAlbum,
							currentAlbum);

					// change status service widget
					WidgetUpdateService.statusCurrentAlbum = true;

					dialog.dismiss();
					// isShowDialogAlbumDefault = false;
					finish();
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// isShowDialogAlbumDefault = false;
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	private void initWidget() {
		try {
			txtItemSelected = (TextView) findViewById(R.id.txtItemSelected);
			txtItemSelected.setVisibility(View.INVISIBLE);
			btnAdd = (ImageView) findViewById(R.id.btnAdd);
			btnAdd.setOnClickListener(this);
			btnEdit = (ImageView) findViewById(R.id.btnEdit);
			btnEdit.setOnClickListener(this);
			btnSetting = (ImageView) findViewById(R.id.btnSetting);
			btnSetting.setOnClickListener(this);
			listAlbum = (GridView) findViewById(R.id.listAlbum);
			arrayAlbum = new ArrayList<ObjectAlbum>();
			loadDBAlbum();
			adapter = new AdapterAlbumManage(AlbumManageActivity.this,
					arrayAlbum);
			listAlbum.setAdapter(adapter);
			listAlbum.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if (dialog == null || dialog.isShowing() == false) {
						Intent intent = new Intent(mContext,
								ImageManageActivity.class);
						intent.putExtra(ConstCommon.KEY_RESULT_ID_ALBUM,
								arrayAlbum.get(position).getIdAlbum());
						startActivityForResult(intent, UPDATE_ALBUM);
					}
				}
			});
			listAlbum.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> parent,
						View view, int position, long id) {
					showDialogUpdateAlbum(arrayAlbum.get(position).getIdAlbum());
					return false;
				}
			});
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private void showImageGallery() {

		Intent intent = new Intent(this, FolderActivity.class);
		intent.putExtra(ConstCommon.KEY_FROM_WHERE_ALBUM,
				ConstCommon.KEY_FROM_WHERE_ALBUM);
		startActivityForResult(intent, CREATE_NEW_ALBUM);
	}

	void loadDBAlbum() {
		try {
			Cursor mCursorAlbum = DBHandler.getAllAlbum(mContext);
			if (mCursorAlbum.moveToFirst()) {
				do {
					ObjectAlbum mObjectAlbum = new ObjectAlbum();
					int idAlbum = mCursorAlbum.getInt(0);
					mObjectAlbum.setIdAlbum(idAlbum);
					mObjectAlbum.setNameAlbum(mCursorAlbum.getString(1));
					mObjectAlbum.setCurrentAlbum(mCursorAlbum.getString(2));

					// get item cover
					Cursor mCursorItemCover = DBHandler.getItemCoverByAlbumId(
							mContext, String.valueOf(idAlbum));
					if (mCursorItemCover.moveToFirst()) {
						ObjectImage mObjectItemCover = new ObjectImage();
						mObjectItemCover.setIdImage(mCursorItemCover.getInt(0));
						mObjectItemCover.setUrlImage(mCursorItemCover
								.getString(1));
						mObjectAlbum.setObjectImageCover(mObjectItemCover);
					}

					// get list item of album
					Cursor mCursorItem = DBHandler.getItemByAlbumId(mContext,
							String.valueOf(idAlbum));
					if (mCursorItem.moveToFirst()) {
						ArrayList<ObjectImage> listItemOfAlbum = new ArrayList<ObjectImage>();
						do {
							ObjectImage mObjectItem = new ObjectImage();
							mObjectItem.setIdImage(mCursorItem.getInt(0));
							mObjectItem.setUrlImage(mCursorItem.getString(1));
							listItemOfAlbum.add(mObjectItem);
						} while (mCursorItem.moveToNext());
						mObjectAlbum.setListImage(listItemOfAlbum);
					}
					arrayAlbum.add(mObjectAlbum);
				} while (mCursorAlbum.moveToNext());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void updateListAlbum(int idAlbum) {
		try {
			Cursor mCursorAlbum = DBHandler.getAlbumById(mContext, idAlbum);
			if (mCursorAlbum.moveToFirst()) {
				ObjectAlbum mObjectAlbum = new ObjectAlbum();
				mObjectAlbum.setIdAlbum(idAlbum);
				mObjectAlbum.setNameAlbum(mCursorAlbum.getString(1));
				mObjectAlbum.setCurrentAlbum(mCursorAlbum.getString(2));

				// get item cover
				Cursor mCursorItemCover = DBHandler.getItemCoverByAlbumId(
						mContext, String.valueOf(idAlbum));
				if (mCursorItemCover.moveToFirst()) {
					ObjectImage mObjectItemCover = new ObjectImage();
					mObjectItemCover.setIdImage(mCursorItemCover.getInt(0));
					mObjectItemCover.setUrlImage(mCursorItemCover.getString(1));
					mObjectAlbum.setObjectImageCover(mObjectItemCover);
				}

				// get list item of album
				Cursor mCursorItem = DBHandler.getItemByAlbumId(mContext,
						String.valueOf(idAlbum));
				if (mCursorItem.moveToFirst()) {
					ArrayList<ObjectImage> listItemOfAlbum = new ArrayList<ObjectImage>();
					do {
						ObjectImage mObjectItem = new ObjectImage();
						mObjectItem.setIdImage(mCursorItem.getInt(0));
						mObjectItem.setUrlImage(mCursorItem.getString(1));
						listItemOfAlbum.add(mObjectItem);
					} while (mCursorItem.moveToNext());
					mObjectAlbum.setListImage(listItemOfAlbum);
				}
				arrayAlbum.add(mObjectAlbum);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void showDialogSelectAddressImport() {
		try {
			final String cbGallery_Selected = mContext.getResources()
					.getString(R.string.gallery);
			final String cbFacebook_Selected = mContext.getResources()
					.getString(R.string.facebook);
			final String cbFlick_Selected = mContext.getResources().getString(
					R.string.flick);
			final String cbInstagram_Selected = mContext.getResources()
					.getString(R.string.instagram);
			cbSelected_Selected = cbGallery_Selected;

			dialog = new Dialog(this);
			dialog.setTitle(getResources().getString(R.string.app_name));
			dialog.setContentView(R.layout.dialog_select_import);
			Button dialog_BtnYes = (Button) dialog
					.findViewById(R.id.dialog_BtnYes);
			Button dialog_BtnNo = (Button) dialog
					.findViewById(R.id.dialog_BtnNo);
			RadioGroup cbGroup = (RadioGroup) dialog.findViewById(R.id.cbGroup);
			cbGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
				public void onCheckedChanged(RadioGroup cbGroup, int checkedId) {
					RadioButton cbSelected = (RadioButton) cbGroup
							.findViewById(checkedId);
					if (cbSelected.isChecked()) {
						cbSelected_Selected = cbSelected.getText().toString();
					}
				}
			});

			dialog_BtnYes.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (cbSelected_Selected.equals(cbGallery_Selected)) {
						showImageGallery();
					} else if (cbSelected_Selected.equals(cbFacebook_Selected)) {
						showImageFacebook();
					} else if (cbSelected_Selected.equals(cbFlick_Selected)) {
						showImageFlickr();
					} else if (cbSelected_Selected.equals(cbInstagram_Selected)) {
						showImageInstagram();
					}
					dialog.dismiss();
				}
			});
			dialog_BtnNo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	void showImageFacebook() {
		Intent intent = new Intent(this, FacebookAlbumActivity.class);
		startActivityForResult(intent, CREATE_NEW_ALBUM);
	}

	void showImageInstagram() {
		Intent intent = new Intent(this, InstagramActivity.class);
		startActivityForResult(intent, CREATE_NEW_ALBUM);
	}

	void showImageFlickr() {
		Intent intent = new Intent(this, FlickrAlbumActivity.class);
		startActivityForResult(intent, CREATE_NEW_ALBUM);
	}
}
